package com.atsmart.app.activity;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnCancelListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.atsmart.app.BizApp;
import com.atsmart.app.R;
import com.atsmart.app.adapter.OtherListAdapter;
import com.atsmart.app.exception.BizException;
import com.atsmart.app.model.ContextInfo;
import com.atsmart.app.model.OtherInfo;
import com.atsmart.app.model.PageInfo;
import com.atsmart.app.model.ResultInfo;
import com.atsmart.app.model.VersionInfo;
import com.atsmart.app.model.VersionListInfo;
import com.atsmart.app.sql.ContextSqlHelper;
import com.atsmart.app.utils.DialogUtil;
import com.atsmart.app.utils.IntentUtil;
import com.atsmart.app.utils.PersistentKeyUtil;
import com.atsmart.app.utils.PrefsUtils;
import com.atsmart.app.utils.StringUtil;
import com.atsmart.app.utils.UpdateUtils;
import com.atsmart.app.webservice.ServiceAsynTask;
import com.atsmart.app.webservice.ServiceHelper;
import com.atsmart.app.webservice.ServiceHost;
import com.google.json.Gson;
import com.google.json.JsonParseException;
import com.google.json.JsonSyntaxException;

/**
 * TODO 其他菜单activity
 */
public class OtherListActivity extends BaseActivity {
	private Spinner spinner;
	private static final String TAG = "OtherListActivity";
	private static String UPDATE_SERVERAPK = "biz.apk";
	private ListView listView;
	private List<OtherInfo> histories;
	private OtherListAdapter adapter;
	private ContextSqlHelper csql = null;
	private Context context;
	/** 判断数据上传事件是否有数据标志位 true：上传 false：不上传 */
	private boolean isReport = false;

	private UpdateUtils updateUtils;
	private String newVerName = "";// 新版本号
	private int newVerCode = -1;// 新版本名称
	private String url = "";// 新版本url
	private Thread th = null;
	/**
	 * 是否中断下载标志位
	 */
	private static boolean flag = false;
	private Dialog dialog;
	private int forcing = 0;
	private static ProgressDialog pd;
	private String[] str = {"高","中", "低"};
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.check_list_layout);

		context = this;
		updateUtils = UpdateUtils.getInstance();
		spinner = (Spinner) findViewById(R.id.check_list_spi);
		ArrayAdapter<String> arradapter = new ArrayAdapter<String>(
				OtherListActivity.this,
				android.R.layout.simple_spinner_item, str);
		arradapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner.setAdapter(arradapter);
		if(PrefsUtils.getIsHighPic() == null || StringUtil.isEmptyOrNull(PrefsUtils.getIsHighPic())){
			spinner.setSelection(0);
			PrefsUtils.setIsHighPic("0");
		}else{
			spinner.setSelection(Integer.parseInt(PrefsUtils.getIsHighPic()));
		}
		spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
					PrefsUtils.setIsHighPic(String.valueOf(arg2));
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				
			}
		});
		
		listView = (ListView) findViewById(R.id.listview);
		csql = new ContextSqlHelper();
		csql.open(BizApp.getInstance().getSqlHelper());
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				OtherInfo otherInfo = (OtherInfo) adapter.getItem(position);
				// if (otherInfo.getId() == -1) {
				// List<ContextInfo> li = csql.getContextInfo();
				//
				// }
				if (otherInfo.getId() == 0) {
					if (isReport) {
						IntentUtil.redirectToNext(context,
								ReportSaveHistoryActivity.class,
								PersistentKeyUtil.HISTORY_TYPE,
								PersistentKeyUtil.REPORT_TYPE_TASK);
					} else {
						Toast.makeText(context, "无任务和汇报工作！", Toast.LENGTH_LONG)
								.show();
					}
				}
				if (otherInfo.getId() == 1) {
					IntentUtil.redirectToNext(context,
							ReportHistoryActivity.class,
							PersistentKeyUtil.HISTORY_TYPE,
							PersistentKeyUtil.REPORT_TYPE_TASK);
				}
				if (otherInfo.getId() == 2) {
					IntentUtil.redirectToNext(context,
							ReportHistoryActivity.class,
							PersistentKeyUtil.HISTORY_TYPE,
							PersistentKeyUtil.REPORT_TYPE_DIRECTLY);
				}
				if (otherInfo.getId() == 3) {
					IntentUtil.redirectToNext(context, CheckActivity.class);
				}

				if (otherInfo.getId() == 4) {
					upEvent();
				}
				
				//TODO
				if (otherInfo.getId() == 5) {
					IntentUtil.redirectToNext(context, LocMsgActivity.class);
				}
			}
		});
	}

	/**
	 * 下载更新事件
	 */
	private void upEvent() {
		if ((BizApp.getInstance().isNetworkAvailable() || BizApp.getInstance().isWiFiActive()) && BizApp.getInstance().keeping) {
			if (updateUtils.isSD()) {
				Log.i(TAG, "准备下载更新！");
				getServerVer();
			} else {
				Toast.makeText(context, "SD卡不可用！", Toast.LENGTH_LONG).show();
			}
		} else {
			Toast.makeText(context, "无可用网络！", Toast.LENGTH_LONG).show();
		}
	}

	/**
	 * 获得版本号
	 */
	public int getVerCode(Context context) {
		int verCode = -1;
		try {
			verCode = context.getPackageManager().getPackageInfo(
					"com.atsmart.app", 0).versionCode;
		} catch (Exception e) {
			Log.e("版本号获取异常", e.getMessage());
		}
		return verCode;
	}

	/**
	 * 获得版本名称
	 */
	public String getVerName(Context context) {
		String verName = "";
		try {
			verName = context.getPackageManager().getPackageInfo(
					"com.atsmart.app", 0).versionName;
		} catch (Exception e) {
			Log.e("版本名称获取异常", e.getMessage());
		}
		return verName;
	}

	/**
	 * 获取服务端版本号，并与当前版本做对比
	 */
	private void getServerVer() {
		try {
			new ServiceAsynTask<VersionListInfo>() {
				/**
				 * 指令上送回调
				 */
				@Override
				protected VersionListInfo callService() throws IOException,
						JsonParseException, AssertionError, BizException ,Exception{
					PageInfo pageInfo = new PageInfo();
					pageInfo.begin = 1;
					pageInfo.end = 1;
					return ServiceHelper.getInstance().postData(
							ServiceHost.versionLocationURL(),
							new Gson().toJson(pageInfo), VersionListInfo.class);
				}

				/**
				 * 处理返回结果回调
				 */
				@Override
				protected void runWithResult(VersionListInfo result)
						throws Exception {
					if (flag == false) {
						dealwithResult(result);
					}
				}
				
				/**
				 * 上送指令异常回调
				 */
				@Override
				protected void runWithError(VersionListInfo result,
						int iErrorCode) throws Exception {
					if(PrefsUtils.getURL().equals(StringUtil.URL1)){
						PrefsUtils.setURL(StringUtil.URL2);
					}else if(PrefsUtils.getURL().equals(StringUtil.URL2)){
						PrefsUtils.setURL(StringUtil.URL1);
					}
					try{
						getServerVerByUrl2();
					}catch (Exception e) {
					}
				}
			}.execute();
		} catch (Exception e) {

		}
	}
	
	private void getServerVerByUrl2() {
		try {
			new ServiceAsynTask<VersionListInfo>() {
				/**
				 * 指令上送回调
				 */
				@Override
				protected VersionListInfo callService() throws IOException,
						JsonParseException, AssertionError, BizException ,Exception{
					PageInfo pageInfo = new PageInfo();
					pageInfo.begin = 1;
					pageInfo.end = 1;
					return ServiceHelper.getInstance().postData(
							ServiceHost.versionLocationURL(),
							new Gson().toJson(pageInfo), VersionListInfo.class);
				}

				/**
				 * 处理返回结果回调
				 */
				@Override
				protected void runWithResult(VersionListInfo result)
						throws Exception {
					if (flag == false) {
						dealwithResult(result);
					}
				}
				
				/**
				 * 上送指令异常回调
				 */
				@Override
				protected void runWithError(VersionListInfo result,
						int iErrorCode) throws Exception {
					if(PrefsUtils.getURL().equals(StringUtil.URL1)){
						PrefsUtils.setURL(StringUtil.URL2);
					}else if(PrefsUtils.getURL().equals(StringUtil.URL2)){
						PrefsUtils.setURL(StringUtil.URL1);
					}
				}
			}.execute();
		} catch (Exception e) {

		}
	}

	/**
	 * 返回结果处理
	 * @param result
	 */
	private void dealwithResult(VersionListInfo result) {
		if (null != result) {
			List<VersionInfo> verlist = result.getVers();
			if (verlist != null && verlist.size() > 0) {
				VersionInfo ver = verlist.get(0);
				newVerCode = ver.getCode();
				newVerName = ver.getVersion();
				url = ver.getUrl();
				forcing = ver.getForcing();
				Log.e("TAG", "service版本信息：= " + new Gson().toJson(result));
				
				int verCode = updateUtils.getVerCode(context);
				if (newVerCode > verCode) {
					UPDATE_SERVERAPK = "biz" + newVerCode + "_" + newVerName + ".apk";
					doNewVersionUpdate();
				} else {
					Toast.makeText(context, "当前版本已是最新版本！", Toast.LENGTH_LONG).show();
				}
			}
		}
	}

	 

	/**
	 * 更新
	 */
	private void doNewVersionUpdate() {
		String verName = updateUtils.getVerName(context);
		StringBuffer sb = new StringBuffer();
		sb.append("当前版本：");
		sb.append(verName);
		sb.append(",发现版本：");
		sb.append(newVerName);
		sb.append(",是否更新");
		flag = true;
		
		if (0 == forcing) {
			dialog = new AlertDialog.Builder(context)
					.setTitle("软件更新")
					.setMessage(sb.toString())
					.setPositiveButton("现在更新",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(
										final DialogInterface dialog, int which) {

									pd = new ProgressDialog(context);
									pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
									pd.setMessage("正在下载更新，请稍候...");
									pd.setCancelable(true);
									pd.setOnCancelListener(new OnCancelListener() {
										@Override
										public void onCancel(
												DialogInterface arg0) {
											pd.dismiss();
											flag = false;
										}
									});
									pd.show();
									if (null != th) {
										th.stop();
									}
									new Thread() {
										public void run() {
											Log.i(TAG, "准备下载--线程");

											GetFileFromUrl(url, Environment.getExternalStorageDirectory()+ "/atsmart".toString());
										}
									}.start();
									dialog.dismiss();
								}
							})
					.setNegativeButton("暂不更新",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									dialog.dismiss();
								}
							}).create();

		} else {
			dialog = new AlertDialog.Builder(context).setTitle("软件更新")
					.setMessage(sb.toString()).create();
		}
		dialog.show();
	}

	private Boolean GetFileFromUrl(String url, String path) {

		long curPosition = 0;
		long startPosition = 0;
		long endPosition = 0;
		long downloadSize = 0;

		long fileLength = 0;
		long localFileLength = 0;

		byte[] b = new byte[51200];

		long progress = 0; // 进度

		URL urlx = null;
		HttpURLConnection con = null;
		InputStream stream = null;

		File file = null;
		RandomAccessFile fos = null;

		File fPath = new File(path);
		if (!fPath.exists())
			fPath.mkdirs();

		file = new File(path, UPDATE_SERVERAPK);

		try {
			fos = new RandomAccessFile(file, "rwd");
			startPosition = fos.length();

			urlx = new URL(url);
			con = (HttpURLConnection) urlx.openConnection();
			con.setAllowUserInteraction(true);// 如果为
												// true，则在允许用户交互（例如弹出一个验证对话框）的上下文中对此
												// URL 进行检查
			con.setConnectTimeout(10 * 1000);
			con.setReadTimeout(10 * 1000);
			con.setRequestMethod("GET");
			con.setRequestProperty("Referer", url);
			con.setRequestProperty("Charset", "UTF-8");
			con.setRequestProperty("Range", "bytes=" + startPosition + "-");// 设置获取实体数据的范围
			con.setRequestProperty("Connection", "Keep-Alive");
			fileLength = con.getContentLength();
			long freeSize = updateUtils.getSDFreeSize();
			
			if(fileLength == -1){//文件判断
				return false;
			} else{//文件存在
				//当freeSize==-1时为获取内存卡大校失败，此时可跳过该步骤
				if(freeSize > fileLength){//剩余磁盘空间大小判断
					
					endPosition = startPosition + fileLength;
					int code = con.getResponseCode();
					
					if (code == 416) {//需要下载文件是否已经存在
						localFileLength = file.length();
						
						if (startPosition == localFileLength) {
							Log.i(TAG, "OK");
							down();// 发送消息关闭对话框
							return true;
						}
					}
					
					//连接网路成功，文件未被下载或未被下载完整
					if (code == HttpURLConnection.HTTP_OK || code == 206) {
						stream = con.getInputStream();

						localFileLength = file.length();
						Log.i(TAG, "返回码为206或者HTTP_OK时locaFileLenght size:" + localFileLength);

						downloadSize += startPosition;
						
						curPosition = startPosition;
						fos.seek(startPosition);
						int count = 0;
						while (curPosition < endPosition && flag) {
							int len = stream.read(b, 0, 51200);

							if (len == -1){
								break;
							}
							fos.write(b, 0, len);

							curPosition = curPosition + len;

							if (curPosition > endPosition) {
								downloadSize += len - (curPosition - endPosition);
							} else {
								downloadSize += len;
							}
							count++;
							if (count > 20) {
								count = 0;
								fos.close();
								fos = new RandomAccessFile(file, "rwd");
								fos.seek(curPosition);

							}
							progress = (long) (((float) downloadSize / endPosition) * 100);
							Log.i(TAG, "progress" + progress);
							//发送消息更新进度条
							Message msg = handler.obtainMessage();
							msg.getData().putInt("step", (int) (progress));
							handler.sendMessage(msg);
						}
						
						stream.close();
						fos.close();
						con.disconnect();
						if(progress == 100){
							down();
						}
					}
				}else{
					Log.i(TAG, "磁盘空间不足");
					Toast.makeText(context, "磁盘空间不足！", Toast.LENGTH_LONG).show();
				}
			}
			
		} catch (Exception e) {
			Log.e(TAG, "下载：" + e.getMessage());
			b = null;
			e.printStackTrace();
		} finally {
			if (null != pd) {
				pd.dismiss();
			}
			try {
				if (null != stream) {
					stream.close();
				}

			} catch (Exception e) {
				Log.e(TAG, "关闭Stream：" + e.getMessage());
			}
		}
	 
		return true;
	}


	final private static Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			int nStep = msg.getData().getInt("step", -1);
			if (nStep == -1) {
				pd.dismiss();
			} else {
				pd.setProgress(nStep);
			}
		}
	};

	/**
	 * 下载完成，通过handler将下载对话框取消
	 */
	public void down() {
		update();
		Message message = handler.obtainMessage();
		handler.sendMessage(message);

	}

	/**
	 * 安装应用
	 */
	public void update() {
		Intent intent = new Intent(Intent.ACTION_VIEW);
		PrefsUtils.setIsPushUp(null);
		intent.setDataAndType(
				Uri.fromFile(new File(Environment.getExternalStorageDirectory()
						.toString() + "/atsmart", UPDATE_SERVERAPK)),
				"application/vnd.android.package-archive");
		startActivity(intent);

	}
	
	@Override
	protected void onResume() {
		super.onResume();
		histories = new ArrayList<OtherInfo>();
		OtherInfo o = new OtherInfo();
		o.setId(0);
		List<ContextInfo> li = csql.getContextInfo();
		int count = 0;
		int count1 = 0;
		if (li != null) {
			for (ContextInfo c : li) {
				if (c.getType() == 0) {
					count++;
				}
				if (c.getType() == 1) {
					count1++;
				}
			}
		}
		//TODO
		// 上传标志位预处理
		isReport = count != 0 || count1 != 0;
		o.setName("数据上传(任务：" + count1 + ",汇报：" + count + ")");
		// o.setName("数据上传");
		// OtherInfo o0 = new OtherInfo();
		// o0.setId(0);
		// o0.setName("产品检索");
		OtherInfo o1 = new OtherInfo();
		o1.setId(1);
		o1.setName("任务历史");
		OtherInfo o2 = new OtherInfo();
		o2.setId(2);
		o2.setName("汇报历史");
		OtherInfo o3 = new OtherInfo();
		o3.setId(3);
		o3.setName("版权信息");

		OtherInfo o4 = new OtherInfo();
		o4.setId(4);
		o4.setName("版本更新");

		OtherInfo o5 = new OtherInfo();
		o5.setId(5);
		o5.setName("当前位置");
		
		histories.add(o);
		// histories.add(o0);
		histories.add(o1);
		histories.add(o2);
		histories.add(o3);
		histories.add(o4);
//		histories.add(o5);
		adapter = new OtherListAdapter(histories);
		listView.setAdapter(adapter);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (event.getKeyCode() == KeyEvent.KEYCODE_BACK
				&& !BizApp.getInstance().isChecking()) {
			DialogUtil.getExitAppDialog(this).show();
			return false;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if(null != pd){
			pd.dismiss();
		}
		flag =false;
	}
}
